import { Component, OnInit, ViewChild } from '@angular/core';
import { Http } from '@angular/http';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { ConfigService } from '../../../core/common/config.service';
import swal from 'sweetalert2';
@Component({
    selector: 'app-areamanage',
    templateUrl: './areamanage.component.html',
    styleUrls: ['./areamanage.component.scss']
})
export class AreamanageComponent implements OnInit {
    @ViewChild('editGroupModal') public editGroupModal: ModalDirective;
    @ViewChild('accountInput') public accountInput;
    @ViewChild('selectedIds') public selectedIds;

    // 新建和编辑项目名称界面的信息切换
    public displayMsg: any = {
        // header: '',
        // confirmBtn: '',
        // type: '',
        // action: ''
    };
    // 项目名称
    public areaName: string;
    // 当前登录的账号信息
    public userInfo: any = {};
    // 表格中展示的信息
    public tabledatas: any = {
        allInfo: [],
        pageInfo: []
    };
    public selectedItems: any = [];
    // 节点或人员表格信息
    public modalTableInfo: any = {
        nodesInfo: [],
        membersInfo: [],
    };
    // 分页配置
    public config: any = {
        paging: true,
        itemsPerPage: 8,
        length: '',
        page: 1,
        maxSize: 5,
        firstText: '|<',
        previousText: '<<',
        nextText: '>>',
        lastText: '>|'
    };
    // 弹出模态框
    public showEditModal(type, action) {
        this.displayMsg.type = type;
        this.displayMsg.action = action;
        this.selectedItems = this.getAccountChecked();
        if (type === 'name') {
            if (action === 'new') {
                this.areaName = '';
                this.displayMsg.header = '新建项目';
                this.displayMsg.confirmBtn = '创建';
                this.editGroupModal.show();
            } else {
                if (this.selectedItems.length === 1) {
                    this.displayMsg.header = '编辑项目';
                    this.displayMsg.confirmBtn = '修改';
                    this.areaName = this.selectedItems[0].areaName;
                    this.userInfo.areaId = this.selectedItems[0].areaId;
                    this.editGroupModal.show();
                } else {
                    swal('提示', '请选择一个账号进行编辑', 'warning').catch(swal.noop);
                }
            }
        } else if (type === 'select') {
            if (this.selectedItems.length === 1) {
                if (action === 'node') {
                    // 获取节点列表
                    this.getNodeList();
                    this.displayMsg.header = '选择节点';
                    this.displayMsg.confirmBtn = '选择';
                } else {
                    // 获取用户列表
                    this.getUserList();
                    this.displayMsg.header = '选择人员';
                    this.displayMsg.confirmBtn = '选择';
                }
                this.editGroupModal.show();
            } else {
                swal('提示', '请选择一个账号进行操作', 'warning').catch(swal.noop);
            }
        } else {
            if (this.selectedItems.length === 1) {
                this.deleteGroup(this.selectedItems[0].areaId);
            } else {
                swal('提示', '请选择一个账号进行操作', 'warning').catch(swal.noop);
            }
        }
    }
    // 获取分组管理表格信息
    public getGroupList(id) {
        try {
            const activateAccount_url = this.configService.get('url') + '?service=CustAreaService&method=getCustAreaList';
            this.http.post(activateAccount_url, { 'custId': id, 'type': '1' }).toPromise().then((data: any) => {
                const dataInfo = data.json();
                if (dataInfo.code === '0000') {
                    this.tabledatas.allInfo = dataInfo.info;
                    this.config.length = this.tabledatas.allInfo.length;
                    this.pageChanged(this.config);
                } else {
                    console.log(dataInfo.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        };
    }
    // 分页功能
    public pageChanged(event) {
        this.tabledatas.pageInfo = this.tabledatas.allInfo.slice(
            (event.page - 1) * this.config.itemsPerPage, event.page * this.config.itemsPerPage);
        this.tabledatas.pageInfo.forEach((value, index) => {
            value.usersStr = value.users.map((val) => {
                return val.userName;
            }).join(' , ');
            value.nodesStr = value.nodes.map((val) => {
                return val.nodeName;
            }).join(' , ');
        });
    }
    // 编辑分组名称
    public editGroupName(msg) {
        let editName_url = '';
        const updataInfo: any = {
            areaName: this.areaName,
        };
        if (msg === 'new') {
            editName_url = this.configService.get('url') + '?service=CustAreaService&method=createCustAreaInfo';
            updataInfo.custId = this.userInfo.custId;
        } else {
            editName_url = this.configService.get('url') + '?service=CustAreaService&method=updateCustAreaInfo';
            updataInfo.areaId = this.userInfo.areaId;
        }
        try {
            this.http.post(editName_url, updataInfo).toPromise().then((data: any) => {
                const dataInfo = data.json();
                if (dataInfo.code === '0000') {
                    this.getGroupList(this.userInfo.custId);
                    this.editGroupModal.hide();
                } else {
                    swal('失败', dataInfo.message, 'error').catch(swal.noop);
                }
            });
        } catch (e) {
            // TODO handle exception
        };
    }
    // 获取节点列表
    public getNodeList() {
        try {
            const activateAccount_url = this.configService.get('url') + '?service=QueryInfoService&method=getNodesByUser';
            this.http.post(activateAccount_url, null).toPromise().then((data: any) => {
                const dataInfo = data.json();
                if (dataInfo.code === '0000') {
                    this.modalTableInfo.nodesInfo = dataInfo.info;
                    this.getGroupById(this.selectedItems[0].areaId)[0].nodes.forEach(value => {
                        this.modalTableInfo.nodesInfo.forEach(ele => {
                            if (ele.nodeId == value.nodeId) {
                                ele.checked = true;
                                return;
                            }
                        });
                    });
                } else {
                    console.log(dataInfo.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        };
    }
    // 获取用户列表
    public getUserList() {
        try {
            const activateAccount_url = this.configService.get('url') + '?service=CustUserService&method=getCustUserList';
            this.http.post(activateAccount_url, null).toPromise().then((data: any) => {
                const dataInfo = data.json();
                if (dataInfo.code === '0000') {
                    this.modalTableInfo.membersInfo = dataInfo.info;
                    this.getGroupById(this.selectedItems[0].areaId)[0].users.forEach(value => {
                        this.modalTableInfo.membersInfo.forEach(ele => {
                            if (ele.userId == value.userId) {
                                ele.checked = true;
                                return;
                            }
                        });
                    });
                } else {
                    console.log(dataInfo.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        };
    }
    // 用户增删
    public memberManage() {
        const infos: any = { add: [], del: [] };
        const newMembers = this.getMemberChecked('userId');
        const groupMembers = this.getGroupById(this.selectedItems[0].areaId)[0].users.map((msg) => {
            return { userId: msg.userId.toString(), relInstId: msg.relInstId.toString() };
        });
        newMembers.forEach(newVal => {
            let isExist = false;
            let i = -1;
            groupMembers.forEach((groVal, index) => {
                if (newVal.userId === groVal.userId) { isExist = true; i = index; }
            });
            if (isExist) {
                groupMembers.splice(i, 1);
            } else {
                newVal.areaId = this.selectedItems[0].areaId;
                infos.add.push(newVal);
            }
        });
        infos.del = groupMembers;
        if (infos.add.length > 0 || infos.del.length > 0) {
            try {
                const memberManage_url = this.configService.get('url') + '?service=CustAreaUserService&method=batchDealCustAreaUser';
                this.http.post(memberManage_url, infos).toPromise().then((data: any) => {
                    const dataInfo = data.json();
                    if (dataInfo.code === '0000') {
                        // 获取分组管理表格信息
                        this.getGroupList(this.userInfo.custId);
                        this.editGroupModal.hide();
                    } else {
                        swal('失败', dataInfo.message, 'error').catch(swal.noop);
                    }
                });
            } catch (e) {
                // TODO handle exception
            };
        } else {
            this.editGroupModal.hide();
        }
    }
    // 节点增删
    public nodeManage() {
        const infos: any = { add: [], del: [] };
        const newMembers = this.getMemberChecked('nodeId');
        const groupMembers = this.getGroupById(this.selectedItems[0].areaId)[0].nodes.map((msg) => {
            return { nodeId: msg.nodeId.toString(), relInstId: msg.relInstId.toString() };
        });
        newMembers.forEach(newVal => {
            let isExist = false;
            let i = -1;
            groupMembers.forEach((groVal, index) => {
                if (newVal.nodeId === groVal.nodeId) { isExist = true; i = index; }
            });
            if (isExist) {
                groupMembers.splice(i, 1);
            } else {
                newVal.areaId = this.selectedItems[0].areaId;
                infos.add.push(newVal);
            }
        });
        infos.del = groupMembers;
        if (infos.add.length > 0 || infos.del.length > 0) {
            try {
                const nodeManage_url = this.configService.get('url') + '?service=CustAreaNodeService&method=batchDealCustAreaNode';
                this.http.post(nodeManage_url, infos).toPromise().then((data: any) => {
                    const dataInfo = data.json();
                    if (dataInfo.code === '0000') {
                        // 获取分组管理表格信息
                        this.getGroupList(this.userInfo.custId);
                        this.editGroupModal.hide();
                    } else {
                        swal('失败', dataInfo.message, 'error').catch(swal.noop);
                    }
                });
            } catch (e) {
                // TODO handle exception
            };
        } else {
            this.editGroupModal.hide();
        }
    }
    // 根据id搜索分组信息
    public getGroupById(id) {
        return this.tabledatas.allInfo.filter(value => {
            return value.areaId === id;
        });
    }
    // 删除分组
    public deleteGroup(id) {
        swal({
            title: '警告',
            text: '删除后不可恢复!',
            type: 'warning',
            showCancelButton: true,
            cancelButtonText: '取消',
            confirmButtonColor: '#4C91EA',
            confirmButtonText: '删除'
        }).then(() => {
            const delGroup_url = this.configService.get('url') + '?service=CustAreaService&method=deleteCustAreaInfo';
            this.http.post(delGroup_url, { areaId: id }).toPromise().then((data: any) => {
                const dataInfo = data.json();
                if (dataInfo.code === '0000') {
                    // 获取分组管理表格信息
                    this.getGroupList(this.userInfo.custId);
                } else {
                    swal('失败', dataInfo.message, 'error').catch(swal.noop);
                }
            });
        }).catch(swal.noop);
    }
    constructor(private http: Http, public configService: ConfigService) {
        // 获取当前登录账号信息
        try {
            const userInfo_url = this.configService.get('url') + '?service=QueryInfoService&method=getCustInfoByUser';
            this.http.post(userInfo_url, null).toPromise().then((data: any) => {
                const dataInfo = data.json();
                if (dataInfo.code === '0000') {
                    this.userInfo = dataInfo.info;
                    // 获取分组管理表格信息
                    this.getGroupList(this.userInfo.custId);
                } else {
                    console.log(dataInfo.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        };
    }
    ngOnInit() { }
    // 获取分组表格中被选中的账号信息
    public getAccountChecked() {
        return $(this.accountInput.nativeElement).find(':checked').map(function () {
            return { areaName: $(this).val(), areaId: $(this).attr('id') };
        }).get();
    }
    // 获取弹出框表格中选中的账号信息
    public getMemberChecked(msg) {
        return $(this.selectedIds.nativeElement).find(':checked').map(function () {
            if (msg === 'nodeId') {
                return { custId: $(this).val(), nodeId: $(this).attr('id') };
            } else {
                return { custId: $(this).val(), userId: $(this).attr('id') };
            }
        }).get();
    }
}
